<?php
/**
 * Created by PhpStorm.
 * User: 93195
 * Date: 2018/7/18
 * Time: 16:57
 */
class ContentStatisticsAction extends Action
{
    /**内容统计页面数据返回
     * @param string $ids 文章id集合，用逗号隔开
     * @param $startTime
     * @param $endTime
     */
    public function index($ids = '', $startTime, $endTime)
    {
        //验证登录
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        //组织查询数据
//        $arr_ids = explode(',', $ids);

        $datas = [
            '文章分享数',
            '总阅读次数',
            '员工分享数',
            '普通好友分享数',
            '表单填写数',
//            '文章参加活动数',
            '奖励红包数',
            '奖励实物礼品数',
            '奖励虚拟礼品数',
//            '用户停留时间'
        ];
        $dataKey = [
            '文章分享数' => 'shareNum',
            '总阅读次数' => 'visitNum',
            '员工分享数' => 'emShareNum',
            '普通好友分享数' => 'frdShareNum',
            '表单填写数' => 'formNum',
//            '文章参加活动数' => 'actNum',
            '奖励红包数' => 'redNum',
            '奖励实物礼品数' => 'vslNum',
            '奖励虚拟礼品数' => 'vitNum',
//            '用户停留时间' => 'time'
        ];
        $legendData = [];
        $series = [];
        $xAxisData = [];
        $arr_sumSumNumList = []; //用于储存每个指标的sumSumNum
        foreach ($datas as $data) {
            $legendData[] = $data;
            $sumSumNum = 0; //每个指标所有文章所有日期内的总和
            $seriesData = [];
            $xAxisData = [];
            for ($i = 0; $i <= $this->daysCountBetweenTwoDays($startTime, $endTime); $i++) {
                $time = date('Y-m-d', strtotime($startTime . ' +' . $i . ' day'));
                $start_time = $time . ' 00:00:00';
                $end_time = $time . ' 23:59:59';

//                foreach ($arr_ids as $id) {
                    switch ($data) {
                        case '文章分享数':
                            $num = $this->getContentShareNum($ids, $start_time, $end_time);
                            break;
                        case '总阅读次数':
                            $num = $this->getContentVisitNum($ids, $start_time, $end_time);
                            break;
                        case '员工分享数':
                            $num = $this->getSaleSourceShareNum($ids, $start_time, $end_time);
                            break;
                        case '普通好友分享数':
                            $num = $this->getFriendsShareNum($ids, $start_time, $end_time);
                            break;
                        case '表单填写数':
                            $num = $this->getFormOrderNum($ids, $start_time, $end_time);
                            break;
                        case '文章参加活动数':
                            $num = $this->getJoinActivityNum($ids, $start_time, $end_time);
                            break;
                        case '奖励红包数':
                            $num = $this->getShareRewardNum($ids, $start_time, $end_time, 1);
                            break;
                        case '奖励实物礼品数':
                            $num = $this->getShareRewardNum($ids, $start_time, $end_time, 2);
                            break;
                        case '奖励虚拟礼品数':
                            $num = $this->getShareRewardNum($ids, $start_time, $end_time, 3);
                            break;
                        case '用户停留时间':
                            $num = $this->getContentVisitTime($ids, $start_time, $end_time);
                            if (empty($num)) $num = '0';
                            break;
                        default:
                            break;
                    }

                    $sumNum = $num;
                    $seriesData[] = $sumNum;
                    $xAxisData[] = $time;
//                }
                $sumSumNum += $sumNum;
            }
            $series_i = ['name' => $data, 'data' => $seriesData];
            array_push($series, $series_i);
            $arr_sumSumNumList[$dataKey[$data]] = $sumSumNum;
        }

        Output::instance()->object([
            'code' => 0,
            'msg' => '',
            'data' => [
                'legendData' => $legendData,
                'xAxisDate' => $xAxisData,
                'series' => $series,
                'sumDataList' => $arr_sumSumNumList
            ]
        ]);
    }

    /*********************************************以下为私有方法********************************************************/

    /**获取文章分享数
     * @param int $id 文章id
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    private function getContentShareNum($id, $startTime, $endTime)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mishareFromModel = M('mishare_from');
        Session::switchCustomer($customerId);

        $where = [
            'module' => 'micontent',
            'createTime' => ['between', [$startTime, $endTime]]
        ];
        $id ? $where['moduleId'] = ['in', $id] : $where['cid'] = $customerId;

        $result = $mishareFromModel->where($where)->count();
        return $result;
    }

    /**获取员工转发数
     * @param $id
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    private function getSaleSourceShareNum($id, $startTime, $endTime)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mishareFromModel = M('mishare_from');
        Session::switchCustomer($customerId);

        $where = [
            'module' => 'micontent',
            'createTime' => ['between', [$startTime, $endTime]],
            'saleSourceUid' => ['gt', 0]
        ];
        $id ? $where['moduleId'] = ['in', $id] : $where['cid'] = $customerId;

        $result = $mishareFromModel->where($where)->count();
        return $result;
    }

    /**获取好友转发数
     * @param $id
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    private function getFriendsShareNum($id, $startTime, $endTime)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mishareFromModel = M('mishare_from');
        Session::switchCustomer($customerId);

        $where = [
            'module' => 'micontent',
            'createTime' => ['between', [$startTime, $endTime]],
            'saleSourceUid' => 0
        ];
        $id ? $where['moduleId'] = ['in', $id] : $where['cid'] = $customerId;

        $result = $mishareFromModel->where($where)->count();
        return $result;
    }

    /**获取总阅读人数
     * @param $id
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    private function getContentVisitNum($id, $startTime, $endTime)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mishareVisitModel = M('mishare_visit');
        Session::switchCustomer($customerId);

        $where = [
            'module' => 'micontent',
            'createTime' => ['between', [$startTime, $endTime]]
        ];
        $id ? $where['moduleId'] = ['in', $id] : $where['cid'] = $customerId;

        $result = $mishareVisitModel->where($where)->count();
//        $result = count($result);
        return $result;
    }

    /**获取用户停留时间（s）
     * @param $id
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    private function getContentVisitTime($id, $startTime, $endTime)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mishareVisitModel = M('mishare_visit');
        Session::switchCustomer($customerId);

        $where = [
            'module' => 'micontent',
            'createTime' => ['between', [$startTime, $endTime]]
        ];
        $id ? $where['moduleId'] = ['in', $id] : $where['cid'] = $customerId;

        $result = $mishareVisitModel->where($where)->field('sum(visitTime) as time')->select();
        return $result[0]['time'];
    }

    /**获取表单填写数
     * @param $id
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    private function getFormOrderNum($id, $startTime, $endTime)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $orderModel = M('module_product_order');
        Session::switchCustomer($customerId);

        $where = [
            'o.type' => 'form',
            'o.createTime' => ['between', [$startTime, $endTime]]
        ];
        $id ? $where['d.contentId'] = ['in', $id] : $where['o.fromCustomerId'] = $customerId;

        $result = $orderModel->alias('o')
            ->join('wx_module_product_order_detail d on d.oid = o.id')
            ->where($where)
            ->count();

        return $result;
    }

    /**获取分享奖励数据
     * @param $id
     * @param $startTime
     * @param $endTime
     * @param int $rewardWay 奖励方式1红包2实物3虚拟
     * @return mixed
     */
    private function getShareRewardNum($id, $startTime, $endTime, $rewardWay)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $shareRewardResultModel = M('share_reward_result');
        Session::switchCustomer($customerId);

        $where = [
            'module' => 'micontent',
            'createTime' => ['between', [$startTime, $endTime]],
            'rewardWay' => $rewardWay,
            'status' => 1
        ];
        $id ? $where['moduleId'] = ['in', $id] : $where['cid'] = $customerId;

        $result = $shareRewardResultModel->where($where)->count();

        return $result;
    }

    /**获取参加活动数
     * @param $id
     * @param $startTime
     * @param $endTime
     * @return int
     */
    private function getJoinActivityNum($id, $startTime, $endTime)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);

        Session::switchCustomer($customerId);

        $where = [];

        $result = '0';

        return $result;
    }

    /**获取两个日期之间的天数
     * @param $startTime
     * @param $endTime
     * @return float
     */
    private function daysCountBetweenTwoDays($startTime, $endTime)
    {
        $startSeconds = strtotime($startTime);
        $endSeconds = strtotime($endTime);

        if ($startSeconds > $endSeconds) {
            $temp = $endSeconds;
            $endSeconds = $startSeconds;
            $startSeconds = $temp;
        }

        return floor(($endSeconds - $startSeconds) / 86400);
    }
}